package com.mdxx.patrol.system.service.impl;

import com.mdxx.patrol.system.param.*;
import com.mdxx.patrol.system.service.IDeptService;
import com.mdxx.patrol.system.service.IMemberService;
import com.mdxx.patrol.system.vo.EmpAllListVo;
import com.mdxx.patrol.system.vo.MemberQueryByRoleListVo;
import com.mdxx.patrol.system.vo.MemberQueryListVo;
import com.mdxx.base.realm.PasswordHelper;
import com.mdxx.common.CommonResult;
import com.mdxx.common.ResultFactory;
import com.mdxx.common.TableData;
//import com.mdxx.patrol.server.base.realm.PasswordHelper;
import com.mdxx.patrol.system.bean.*;
import com.mdxx.patrol.system.mapper.SysDeptMapper;
import com.mdxx.patrol.system.mapper.SysEmployeeMapper;
import com.mdxx.patrol.system.mapper.SysMemberMapper;
import com.mdxx.patrol.system.mapper.SysRoleMapper;
import org.apache.commons.lang.time.FastDateFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by MD-01 on 2017/5/17.
 */
@Service
@Transactional
public class MemberServiceImpl implements IMemberService {

    @Resource
    private IDeptService deptService;
    @Resource
    private SysMemberMapper memberMapper;
    @Resource
    private SysDeptMapper deptMapper;
    @Resource
    private SysEmployeeMapper employeeMapper;
    @Resource
    private SysRoleMapper roleMapper;
    @Resource
    private PasswordHelper helper;

    @Override
    public CommonResult<TableData<MemberQueryListVo>> queryList(MemberQueryListParam param) {

        CommonResult<List<Integer>> deptResult = deptService.getMyDeptIdList();

        //如果查询到的部门列表为空.返回空数据
        if(deptResult.getCode()!=0 || deptResult.getData().size()==0){
            TableData<MemberQueryListVo> data = new TableData<>();
            data.setData(new ArrayList<>());
            data.setRecordsTotal(0);
            data.setRecordsFiltered(0);
            return ResultFactory.ok(data);
        }

        List<SysMember> sysMembers = memberMapper.queryList(param.getStart(), param.getNum(),
                param.getKey(), deptResult.getData());

        List<MemberQueryListVo> vos = new ArrayList<>();
        FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
        for(SysMember member : sysMembers){
            MemberQueryListVo vo = new MemberQueryListVo();
            vo.setDeptId(member.getDeptId());
            SysDept dept = deptMapper.selectById(member.getDeptId());
            if(dept!=null){
                vo.setDeptName(dept.getName());
            }
            vo.setEmployeeId(member.getEmployeeId());
            SysEmployee employee = employeeMapper.selectById(member.getEmployeeId());
            if(employee!=null){
                vo.setEmployeeName(employee.getName());
                vo.setPhoneNum(employee.getPhoneNum());
            }
            if(member.getLastLoginTime()!=null){
                vo.setLastLoginTime(format.format(member.getLastLoginTime()));
            }
            vo.setMemberId(member.getId());
            vo.setUsable(member.getUsable());
            vo.setUsername(member.getUsername());

            List<SysRole> roleList = roleMapper.queryByMemberId(member.getId());
            for(SysRole role : roleList){
                vo.getRoleIds().add(role.getId());
                vo.getRoleNames().add(role.getName());
            }
            vos.add(vo);
        }
        int count = memberMapper.queryListCount(param.getKey(),deptResult.getData());
        TableData<MemberQueryListVo> data = new TableData<>();
        data.setRecordsFiltered(count);
        data.setRecordsTotal(count);
        data.setData(vos);

        return ResultFactory.ok(data);
    }

    @Override
    public CommonResult<Void> save(MemberSaveParam param) {
        if(StringUtils.isEmpty(param.getUsername())){
            return ResultFactory.error("用户名不能为空");
        }
        SysMember member = memberMapper.selectById(param.getMemberId());
        if(member==null){
            return ResultFactory.error("错误的用户编号");
        }
        member.setUsername(param.getUsername());
        member.setUsable(param.getUsable());
        memberMapper.deleteMemberRole(param.getMemberId());
        for(Integer roleId : param.getRoleIdList()){
            memberMapper.insertMemberRole(param.getMemberId(),roleId);
        }
        memberMapper.updateById(member);
        return ResultFactory.ok();
    }

    /**
     * 修改密码
     */
    public CommonResult<Void> changePassword(MemberChangePasswordParam param) {

        SysMember member = memberMapper.selectById(param.getMemberId());
        if(member==null){
            return ResultFactory.error("错误的用户编号");
        }
        String salt = member.getSalt();
        String dbPassword = member.getPassword();

        String inputPassword = param.getOldPassword();//helper.calculatePassword(param.getOldPassword(),salt);
        if(!inputPassword.equals(dbPassword)){
            return ResultFactory.error("旧密码输入错误");
        }

        member.setPassword(param.getNewPassword());
        helper.encryptPassword(member);
        memberMapper.updateById(member);
        return ResultFactory.ok();
    }


    /**
     * 创建用户
     */
    public CommonResult<Void> createMember(MemberCreateMemberParam param) {

        SysMember member = memberMapper.queryByUsername(param.getUsername());
        if(member!=null){
            return ResultFactory.error("该用户名已经存在");
        }
        member = new SysMember();
        member.setPassword(param.getPassword());
        member.setUsable(1);
        member.setUsername(param.getUsername());
        member.setCreateTime(new Date());
        member.setEmployeeId(param.getEmployeeId());
        member.setDeptId(param.getDeptId());
        helper.encryptPassword(member);
        memberMapper.insert(member);
        return ResultFactory.ok();
    }


    @Override
    public CommonResult<List<MemberQueryByRoleListVo>> queryListByRoleId(MemberQueryByRoleParam param) {
        CommonResult<List<Integer>> deptResult = deptService.getMyDeptIdList();
        List<SysMember> empList=memberMapper.queryByRoleId(param.getRoleId(),deptResult.getData());
        List<MemberQueryByRoleListVo> vos=new ArrayList<>();
        for(SysMember member:empList){
            MemberQueryByRoleListVo vo=new MemberQueryByRoleListVo();
            SysEmployee employee=employeeMapper.selectById(member.getEmployeeId());
            vo.setEmployeeName(employee.getName());
            SysDept dept=deptMapper.selectById(member.getDeptId());
            vo.setDeptName(dept.getName());
            vo.setEmployeeId(member.getEmployeeId());
            vo.setMemberId(member.getId());
            vos.add(vo);
        }
        return ResultFactory.ok(vos);
    }
}
